package ec.espol.edu.isi.grupo2.academicoicefenix;

import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.widget.*;
import java.io.*;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;

public class Context {
	public static StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	
	public static String CAS_SERVER = "https://auth.espol.edu.ec";
	public static String SERVICE = "academicoicefenix%3A%2F%2F";
	
	public static String ticket = null;
	public static Usuario usuario = null;
	
	private static Activity lastActivity = null;
	
	public static void verifyLogin(Activity activity) {
		usuario = null;
		String result = "";

		if (ticket == null) {
			redirectToCAS(activity);
			return;
		}

		try {
			HttpClient httpClient = SSLAllowAllSocketFactory.getNewHttpClient();
			
			HttpGet httpget = new HttpGet(CAS_SERVER+"/validate?ticket="+ticket+"&service="+SERVICE);
			HttpResponse resp = httpClient.execute(httpget);
			
			result = getStringFromStream(resp.getEntity().getContent());
			String params[] = result.split("\n");
			if (params[0].equals("no")) {
				redirectToCAS(activity);
				return;
			} else {
				result = params[1];
				usuario = WsClient.wsInfoUsuario(result);
				Toast.makeText(activity, "Bienvenido, "+usuario.getNombre(), Toast.LENGTH_SHORT).show();
				activity.startActivity(new Intent(activity, HomeActivity.class));
				activity.finish();
			}
		} catch (Exception e) {
			redirectToCAS(activity);
			return;
		}
	}
	
	private static void redirectToCAS(final Activity activity) {
		lastActivity = activity;
		Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(CAS_SERVER+"/login?service="+SERVICE));
		activity.startActivity(intent);
		activity.finish();
	}
	
	private static String getStringFromStream(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
		} finally {
			try {
				is.close();
			} catch (IOException e) {}
		}

		return sb.toString();
	}
}
